//
//  HCUtilities.m
//  HCToolBox
//
//  Created by Hotacool on 2019/4/17.
//

#import <UIKit/UIKit.h>
#import "HCUtilities.h"

NSString *const kHCTBBundleName = @"XYZQLogConsole.bundle";
@implementation HCUtilities

@end

@implementation HCUtilities (Resource)
/** in local framework  */
+ (nullable NSBundle *)resourcesBundle {
    return [HCUtilities resourcesBundleWithName:kHCTBBundleName inClass:[self class]];
}

+ (nullable UIImage *)imageWithName:(nullable NSString *)name {
    NSBundle *bundle = [HCUtilities resourcesBundle];
    return [HCUtilities imageInBundle:bundle withName:name];
}

+ (nullable NSBundle *)resourcesBundleWithName:(nullable NSString *)bundleName inClass:(Class)class {
    NSBundle *bundle = [NSBundle bundleWithPath: [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:bundleName]];
    if (!bundle) {
        NSBundle *frameworkBundle = [NSBundle bundleForClass:class];
        NSDictionary *bundleData = [self parseBundleName:bundleName];
        if (bundleData) {
            bundle = [NSBundle bundleWithPath:[frameworkBundle pathForResource:[bundleData objectForKey:@"name"] ofType:[bundleData objectForKey:@"type"]]];
        }
    }
    return bundle;
}

+ (nullable UIImage *)imageInBundle:(nullable NSBundle *)bundle withName:(nullable NSString *)name {
    if (bundle && name) {
        if ([UIImage respondsToSelector:@selector(imageNamed:inBundle:compatibleWithTraitCollection:)]) {
            return [UIImage imageNamed:name inBundle:bundle compatibleWithTraitCollection:nil];
        } else {
            NSString *imagePath = [[bundle resourcePath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", name]];
            return [UIImage imageWithContentsOfFile:imagePath];
        }
    }
    return nil;
}

+ (NSDictionary *)parseBundleName:(NSString *)bundleName {
    NSArray *bundleData = [bundleName componentsSeparatedByString:@"."];
    if (bundleData.count == 2) {
        return @{@"name":bundleData[0], @"type":bundleData[1]};
    }
    return nil;
}
@end
